package cz.zcu.fav.rat.managed.bean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import cz.zcu.fav.rat.beans.Object;
import cz.zcu.fav.rat.beans.ObjectClass;
import cz.zcu.fav.rat.dataaccess.service.ObjectClassService;
import cz.zcu.fav.rat.dataaccess.service.ObjectService;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

@ManagedBean
@ViewScoped
public class EditObjectBean extends AbstractEditBean
{
	private static final long serialVersionUID = 1798377038256057225L;
	private Object selectedObject;
	private List<ObjectClass> objectClasses;
	private ObjectClass selectedObjectClass;

	@PostConstruct
	public void init()
	{
		super.init();
		if (id != null)
		{
			selectedObject = getObjectService().get(id);
		} else
		{
			selectedObject = new Object();
			objectClasses = getObjectClassService().getAll();
		}
	}

	public void create()
	{
		selectedObject.setObjectClass(selectedObjectClass);
		getObjectService().create(selectedObject);

		selectedObject = new Object();
		String message = LocaleMessageFactory
				.getLocale("view.objectcreate.info.objectcreated");

		FacesContext.getCurrentInstance().addMessage("form",
				new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
	}

	public String edit()
	{
		getObjectService().update(selectedObject);
		return "objecttable?faces-redirect=true";
	}

	private ObjectService getObjectService()
	{
		return SpringBeanFactory.getInstance().<ObjectService> getBean(
				"objectService", ObjectService.class);
	}

	private ObjectClassService getObjectClassService()
	{
		return SpringBeanFactory.getInstance().<ObjectClassService> getBean(
				"objectClassService", ObjectClassService.class);
	}

	public List<ObjectClass> getObjectClasses()
	{
		return objectClasses;
	}

	public void setId(Integer id)
	{
		this.id = id;
	}

	public Object getSelectedObject()
	{
		return selectedObject;
	}

	public void setSelectedObject(Object selectedObject)
	{
		this.selectedObject = selectedObject;
	}

	public ObjectClass getSelectedObjectClass()
	{
		return selectedObjectClass;
	}

	public void setSelectedObjectClass(ObjectClass selectedObjectClass)
	{
		this.selectedObjectClass = selectedObjectClass;
	}
}
